package com.lalosoft.gastostarjetaweb.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.lalosoft.gastostarjetaweb.model.User;
import com.lalosoft.gastostarjetaweb.pmf.PMF;



public class UserDao {
	
	private static final Logger log = Logger.getLogger("UserDao");
	
	public static List<User> findAll(PersistenceManager pm){
		List<User> list = new ArrayList<User>();
		Query q = pm.newQuery(User.class);
		list = (List<User>)q.execute();
		return list;
	}
	
	public static User findUserByEmail(String email){
		User user = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Query q = pm.newQuery(User.class);
			List<User> list = (List<User>) q.execute();
			if(list.size() > 0){
				for(User temp : list){
					if(temp.getEmail().equals(email)){
						user = temp;
					}
				}
			}
		}finally {
			pm.close();
		}
		return user;
	}
	
	public static User getUser(String email, String password){
		User user = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query q = pm.newQuery(User.class);
			List<User> list = (List<User>)q.execute();
			for(User temp : list){
				if(temp.getEmail().equals(email) && temp.getPassword().equals(password)){
					user = temp;
				}
			}
		} finally {
			pm.close();
		}
		return user;
	}
	
	public static User findByToken(String token, PersistenceManager pm){
		User user = null;
		Query q = pm.newQuery(User.class);
		List<User> list = (List<User>)q.execute();
		for(User temp : list){
			if(temp.getUuid().equals(token)){
				user = temp;
			}
		}
		return user;
	}
	
	public static void updateUser(User user, PersistenceManager pm){
		pm.makePersistent(user);
	}
	
	public static String saveUser(User user){
		String uuid = UUID.randomUUID().toString();
		user.setUuid(uuid);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(user);
			log.log(Level.WARNING, "Nuevo usuario guardado");
		} finally {
			pm.close();
		}
		return uuid;
	}

}
